package cn.itsource.pet.controller;

import cn.itsource.basic.utils.LoginContext;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.pet.service.IPetService;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.query.PetQuery;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    public IPetService petService;
    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 保存和修改公用的
     * @param pet  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Pet pet, HttpServletRequest request){
        //给宠物设置店铺id，通过当前登录用户获取
        Logininfo currentUser = LoginContext.getCurrentUser(request);
        Employee employee = employeeMapper.queryByLoginInfoId(currentUser.getId());
        if(employee != null && employee.getShopId() != null){
            pet.setShopId(employee.getShopId());
        }
        try {
            if(pet.getId()!=null){
                petService.update(pet);
            }
            else{
                petService.add(pet);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器忙，请稍后重试");
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            petService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器忙，请稍后重试");
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Pet get(@PathVariable("id")Long id)
    {
        return petService.queryById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Pet> list(){

        return petService.queryAll();
    }


    /**
    * 分页查询数据
    *  主站前端仅显示上架后的宠物 查询需要携带state=1参数
     *  后端管理系统都需要展示 不需要state参数
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<Pet> json(@RequestBody PetQuery query)
    {
        return petService.queryPage(query);
    }
}
